package cn.hznc.controller.service.production;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hznc.configuration.MinioHelper;
import cn.hznc.constant.CommonConstant;

import cn.hznc.controller.service.QuerySqlServerService;
import cn.hznc.controller.service.order.OrderManageService;
import cn.hznc.controller.service.production.logic.ProductionBomDo;
import cn.hznc.controller.service.production.logic.ProductionBomLogic;
import cn.hznc.domain.entity.*;
import cn.hznc.domain.request.process.OperateBomReq;
import cn.hznc.domain.request.production.AddOrEditProductionReq;
import cn.hznc.domain.request.production.QueryProductionReq;
import cn.hznc.domain.response.PageResult;
import cn.hznc.exception.ToolManageEx;
import cn.hznc.exception.ToolManageException;
import cn.hznc.mapper.*;
import cn.hznc.repository.ProductionRespository;
import cn.hznc.utils.CommonUtil;
import cn.hznc.utils.UUIDUtil;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * @Author Administrator
 * @Date 2023/3/16 16:59
 */
@Service
public class ProductionManageService{

    @Resource
    private ProductionMapper productionMapper;

    @Resource
    private ProductionRespository productionRespository;

    @Resource
    private ProductionProcessMapper productionProcessMapper;

    @Resource
    private ProductionBomMapper productionBomMapper;

    @Resource
    private OrderManageService orderManageService;

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private ProcessMapper processMapper;

    @Resource
    private ProcessCraftMapper processCraftMapper;
//
//    @Resource
//    private TestService testService;

    @Resource
    private QuerySqlServerService querySqlServerService;

    @Autowired
    private MinioHelper minioHelper;

    @Autowired
    private MinioProp minioProp;

    /**
     * 分页查询产品列表
     *
     * @return
     */
    public PageResult<ProductionEntity> queryProductionList(QueryProductionReq queryProductionReq) {
        PageHelper.startPage(queryProductionReq.getPageNum(), queryProductionReq.getPageSize());
        LambdaQueryWrapper<ProductionEntity> productionQueryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(queryProductionReq.getMaterialNo())) {
            productionQueryWrapper.like(ProductionEntity::getMaterialNo, queryProductionReq.getMaterialNo());
        }
        if (StringUtils.isNotEmpty(queryProductionReq.getName())) {
            productionQueryWrapper.like(ProductionEntity::getName, queryProductionReq.getName());
        }
        if (StringUtils.isNotEmpty(queryProductionReq.getProductionNum())) {
            productionQueryWrapper.like(ProductionEntity::getProductionNum, queryProductionReq.getProductionNum());
        }
        PageInfo<ProductionEntity> result = new PageInfo<>(productionMapper.selectList(productionQueryWrapper));
        String baseurl = minioProp.getBaseUrl() + minioProp.getBucketName() + "/";
        result.getList().forEach(productionEntity -> {
            productionEntity.setImage(baseurl + productionEntity.getImage());
        });
        return new PageResult<>(result.getList(), result.getTotal());
    }

    /**
     * 编辑与修改产品
     *
     * @param addOrEditProductionReq addOrEditProductionReq
     * @return
     */
    public Boolean addOrEditProduction(AddOrEditProductionReq addOrEditProductionReq) throws ToolManageException {
        // 校验
        if (StringUtils.isEmpty(addOrEditProductionReq.getFigureNo())) {
            throw new ToolManageException(ToolManageEx.PRODUCTION_FIGURE_NUM_IS_NULL.getCode(), ToolManageEx.PRODUCTION_FIGURE_NUM_IS_NULL.getMsg());
        }
//        LambdaQueryWrapper<ProductionEntity> productionQueryWrapper = new LambdaQueryWrapper<>();
//        productionQueryWrapper.eq(ProductionEntity::getFigureNo,addOrEditProductionReq.getFigureNo());
//        List<ProductionEntity> productionEntityList = productionMapper.selectList(productionQueryWrapper);
//        if (!CheckUtil.isUniqe(addOrEditProductionReq.getId(),productionEntityList)){
//            throw new ToolManageException(ToolManageEx.PRODUCTION_FIGURE_NUM_REPEAT.getCode(),ToolManageEx.PRODUCTION_FIGURE_NUM_REPEAT.getMsg());
//        }
        // 转换参数
        ProductionEntity productionEntity = new ProductionEntity();
        BeanUtil.copyProperties(addOrEditProductionReq, productionEntity);
        // 持久化
        if (ObjectUtil.isNull(addOrEditProductionReq.getId())) {
            //id为空
            // 新增
            //检查图号是否重复
            checkRepeat(productionEntity);
            productionEntity.setCreateTime(new Date());
            //设置状态位
            productionEntity.setStatus(CommonConstant.NEW_PRODUCTION);
            productionEntity.setProductionBomStatus(CommonConstant.BOM_PRODUCTION_NOT_DONE);
            productionEntity.setProductionProcessConnectStatus(CommonConstant.PRODUCTION_PROCESS_NOT_CONNECT);
            productionEntity.setProcessStatus(CommonConstant.PROCESS_NOT_DONE);
            productionMapper.insert(productionEntity);
            buildConnectOrderStatus(productionEntity);
        } else {
            //id不为空
            // 修改
            productionEntity.setModifyTime(new Date());
            productionRespository.update(productionEntity);
            productionMapper.updateById(productionEntity);
        }
        return Boolean.TRUE;

    }

    private void buildConnectOrderStatus(ProductionEntity productionEntity) {
        List<OrderEntity> updateOrderEntities = new ArrayList<>();
        //处理页面新建的工单
        QueryWrapper<OrderEntity> figureNoWrapper = new QueryWrapper<>();
        figureNoWrapper.eq("material_no", productionEntity.getMaterialNo());
        List<OrderEntity> orderEntities = orderMapper.selectList(figureNoWrapper);
        if (CollectionUtil.isNotEmpty(orderEntities)) {
            orderEntities.forEach(orderEntity -> {
                orderEntity.setStatus(CommonConstant.ORDER_PRODUCTION_CONNECT_NOT_DONE);
                orderEntity.setProductionName(productionEntity.getName());
                orderEntity.setProductionNum(productionEntity.getProductionNum());
                orderEntity.setFigureNo(productionEntity.getFigureNoReload());
                orderEntity.setFigureNoImage(productionEntity.getImage());
                orderEntity.setHeavy(productionEntity.getHeavy());
                updateOrderEntities.add(orderEntity);
            });
        }
        //处理工单导入的工单
        QueryWrapper<OrderEntity> productionNumWrapper = new QueryWrapper<>();
        productionNumWrapper.eq("material_no", productionEntity.getMaterialNo());
        List<OrderEntity> importOrderEntities = orderMapper.selectList(productionNumWrapper);
        if (CollectionUtil.isNotEmpty(importOrderEntities)) {
            importOrderEntities.forEach(orderEntity -> {
                orderEntity.setStatus(CommonConstant.ORDER_PRODUCTION_CONNECT_NOT_DONE);
                orderEntity.setFigureNo(productionEntity.getFigureNo());
                orderEntity.setFigureNoImage(productionEntity.getImage());
                orderEntity.setHeavy(productionEntity.getHeavy());
                updateOrderEntities.add(orderEntity);
            });
            orderMapper.updateBatchById(updateOrderEntities);
        }
    }


    public ProductionEntity getProductionEntity(String materialNo) {
        LambdaQueryWrapper<ProductionEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProductionEntity::getMaterialNo, materialNo);
        return productionMapper.selectOne(wrapper);
    }

    public ProductionEntity getProductionEntityReload(String materialNo) {
        LambdaQueryWrapper<ProductionEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProductionEntity::getFigureNo, materialNo);
        return productionMapper.selectOne(wrapper);
    }

    public void setProductionStatus(ProductionEntity productionEntity) {
        if (Objects.equals(CommonConstant.BOM_PRODUCTION_DONE, productionEntity.getProductionBomStatus()) //物料编辑完成
                && Objects.equals(CommonConstant.PRODUCTION_PROCESS_CONNECT, productionEntity.getProductionProcessConnectStatus()) //已关联工序
                && Objects.equals(CommonConstant.PROCESS_DONE, productionEntity.getProcessStatus())) {
            productionEntity.setStatus(CommonConstant.DONE_PRODUCTION);
            //产品关联工艺后给工单推送快照信息
            QueryWrapper<OrderEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("figure_no", productionEntity.getFigureNo());
            List<OrderEntity> orderEntities = orderMapper.selectList(wrapper);
            if (!CollectionUtil.isEmpty(orderEntities)) {
                orderEntities.forEach(orderEntity -> {
                    if (orderEntity.getStatus()<CommonConstant.ORDER_PRODUCTION_CONNECT_DONE) {
                        //设置工单完成状态以及推送快照数据
                        orderEntity.setStatus(CommonConstant.ORDER_PRODUCTION_CONNECT_DONE);
                        orderManageService.buildOrderSnapShot(orderEntity, CommonConstant.INIT_VERSION);
                        orderMapper.updateById(orderEntity);
                        //orderManageService.buildOrderStatus(orderEntity,CommonConstant.INIT_VERSION , productionEntity);
                    }
                });
            }
        } else {
            productionEntity.setStatus(CommonConstant.NEW_PRODUCTION);
        }
        productionMapper.updateById(productionEntity);
    }

    private void checkRepeat(ProductionEntity productionEntity) throws ToolManageException {
        QueryWrapper<ProductionEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("figure_no", productionEntity.getFigureNo());
        if (!ObjectUtil.isNull(productionMapper.selectOne(wrapper))) {
            //根据图号可以查询到数据,即图号重复
            throw new ToolManageException(ToolManageEx.PRODUCTION_FIGURE_NUM_REPEAT.getCode(), ToolManageEx.PRODUCTION_FIGURE_NUM_REPEAT.getMsg());
        }
    }

    /**
     * 删除产品
     *
     * @param ids ids
     * @return
     */
    public Boolean deleteProduction(List<Integer> ids) throws ToolManageException {
        // 校验
        if (CollectionUtil.isEmpty(ids)) {
            throw new ToolManageException(ToolManageEx.PRODUCTION_ID_IS_NULL.getCode(), ToolManageEx.PRODUCTION_ID_IS_NULL.getMsg());
        }
        productionMapper.deleteBatchIds(ids);
        //删除该产品和工艺关联关系
        ids.forEach(productionId -> {
            QueryWrapper<ProductionProcessEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("production_id", productionId);
            productionProcessMapper.delete(wrapper);
        });
        return Boolean.TRUE;
    }

    public Map<String, Object> upload(MultipartFile file, String materialNo) throws ToolManageException {
        String fileName = "production" + materialNo + ".jpg";
        Map<String, Object> retMap = new HashMap<>();
        minioHelper.uploadFile(file, fileName);
        retMap.put("image", fileName);
        return retMap;
    }

    public Boolean editOrAddBom(OperateBomReq operateBomReq) throws ToolManageException {
        if (StringUtils.isEmpty(operateBomReq.getFigureNo())) {
            throw new ToolManageException(ToolManageEx.PRODUCTION_ID_IS_NULL.getCode(), ToolManageEx.PRODUCTION_ID_IS_NULL.getMsg());
        }
        LambdaQueryWrapper<ProductionBomEntity> wrapper = buildBomWrapper(operateBomReq.getFigureNo(), operateBomReq.getVersion());
        List<ProductionBomEntity> originProcessBomList = productionBomMapper.selectList(wrapper);
        List<ProductionBomEntity> updateProcessBomList = transferProcessBom(operateBomReq);

        ProductionBomLogic productionBomLogic = new ProductionBomLogic(originProcessBomList, updateProcessBomList);
        productionBomLogic.buildProcessBomDo();
        ProductionBomDo productionBomDo = productionBomLogic.getProductionBomDo();
        // 持久化
        persistBom(productionBomDo);
        return Boolean.TRUE;
    }

    private void persistBom(ProductionBomDo productionBomDo) {
        // 删除物料
        List<Integer> deleteIds = productionBomDo.getDeleteElement().stream().map(ProductionBomEntity::getId).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(deleteIds)) {
            productionBomMapper.deleteBatchIds(deleteIds);
        }
        // 新增物料
        if (CollectionUtil.isNotEmpty(productionBomDo.getCreateElement())) {
            productionBomMapper.insertBatchSomeColumn(productionBomDo.getCreateElement());
        }
        // 修改物料
        if (CollectionUtil.isNotEmpty(productionBomDo.getUpdateElement())) {
            productionBomMapper.updateBatchById(productionBomDo.getUpdateElement());
        }
    }

    private LambdaQueryWrapper<ProductionBomEntity> buildBomWrapper(String figureNo, Integer version) {
        LambdaQueryWrapper<ProductionBomEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProductionBomEntity::getFigureNo, figureNo);
        wrapper.eq(ProductionBomEntity::getVersion, version);
        return wrapper;
    }

    private List<ProductionBomEntity> transferProcessBom(OperateBomReq operateBomReq) {
        if (CollectionUtil.isEmpty(operateBomReq.getBatchUpdateReq())) {
            return Collections.emptyList();
        }
        List<ProductionBomEntity> updateProcessBomList = new ArrayList<>();
        for (int i = 0; i < operateBomReq.getBatchUpdateReq().size(); i++) {
            ProductionBomEntity productionBomEntity = new ProductionBomEntity();
            BeanUtil.copyProperties(operateBomReq.getBatchUpdateReq().get(i), productionBomEntity);
            // 重新生成自增序列
            productionBomEntity.setSeq(i + 1);
            if (ObjectUtil.isNull(operateBomReq.getBatchUpdateReq().get(i).getId())) {
                // 新增的重新生成
                productionBomEntity.setVersion(operateBomReq.getVersion());
                productionBomEntity.setFigureNo(operateBomReq.getFigureNo());
                productionBomEntity.setCode("bom" + "-" + UUIDUtil.getUUID());
            }
            updateProcessBomList.add(productionBomEntity);
        }
        return updateProcessBomList;
    }

    /**
     * 查询物料详情
     *
     * @return
     */
    public List<ProductionBomEntity> queryBomDetail(String figureNo, Integer version) {
        LambdaQueryWrapper<ProductionBomEntity> wrapper = buildQueryWrapper(figureNo, version);
        return productionBomMapper.selectList(wrapper);
    }

    private LambdaQueryWrapper<ProductionBomEntity> buildQueryWrapper(String figureNo, Integer version) {
        LambdaQueryWrapper<ProductionBomEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(ProductionBomEntity::getSeq);
        wrapper.eq(ProductionBomEntity::getFigureNo, figureNo);
        wrapper.eq(ProductionBomEntity::getVersion, version);
        return wrapper;
    }

    public void editBomStatus(String materialNo, Integer status) throws ToolManageException {
        ProductionEntity productionEntity = getProductionEntity(materialNo);
        if (ObjectUtil.isNull(productionEntity)) {
            throw new ToolManageException(ToolManageEx.PRODUCTION_ID_IS_NULL.getCode(), ToolManageEx.PRODUCTION_ID_IS_NULL.getMsg());
        }
        productionEntity.setProductionBomStatus(status);
        setProductionStatus(productionEntity);
    }

    public Map<String, Integer> queryBomStatus(String materialNo) throws ToolManageException {
        ProductionEntity productionEntity = getProductionEntity(materialNo);
        Map<String, Integer> bomStatus = new HashMap<>();
        bomStatus.put("bomStatus", productionEntity.getProductionBomStatus());
        return bomStatus;
    }

    public Integer showPeocessStates(String materialNo) {
        LambdaQueryWrapper<ProductionEntity> wrapper = new LambdaQueryWrapper<ProductionEntity>();
        wrapper.eq(ProductionEntity::getMaterialNo, materialNo);
        ProductionEntity productionEntity = productionMapper.selectOne(wrapper);
        if (productionEntity.getProductionProcessConnectStatus() == 0) {
            //未关联状态
            return 2;
        }
        //已关联状态,返回工序状态
        return productionEntity.getProcessStatus();
    }


    public void unbind(String materialNo) {
        if (StringUtils.isNotEmpty(materialNo)) {
            productionRespository.updateStatus(materialNo);
            productionRespository.updataStatusByFigureno(materialNo);
        }
    }

    public List<ProductionEntity> selectBycode(String code) {
        List<Integer> list = productionRespository.selectByCode(code);
        return productionRespository.selectByid(list);
    }

    /**
     * 拉取数据自动关联
     * @return
     */
//    public Object abutmentProduction() {
//        String get = HttpUtil.get(UrlConstant.PROCESS_MANAGEMENT_SYNC_URL + "/abutmentProduction");
//        if(StringUtils.isNotEmpty(get)){
//            List<AbutmentProduction> abutmentProductions = JSONArray.parseArray(get, AbutmentProduction.class);
//            if(CollectionUtil.isNotEmpty(abutmentProductions)){
//                List<ProductionEntity> productionEntities = new ArrayList<>();
//                List<ProcessEntity> processEntities = new ArrayList<>();
//                List<ProcessCraftEntity> processCraftEntities = new ArrayList<>();
//                abutmentProductions.forEach(abutmentProduction -> {
//                    QueryWrapper<ProductionEntity> wrapper = new QueryWrapper<>();
//                    wrapper.eq("material_no" , abutmentProduction.getMaterialNo());
//                    ProductionEntity existProduction = productionMapper.selectOne(wrapper);
//                    if(ObjectUtil.isNotNull(existProduction) || StringUtils.isEmpty(abutmentProduction.getFigureNo())){
//                        return;
//                    }
//                    ProductionEntity productionEntity = new ProductionEntity();
//                    BeanUtil.copyProperties(abutmentProduction , productionEntity);
//                    productionEntity.setHeavy(BigDecimal.valueOf(abutmentProduction.getProductionHeavy()));
//                    productionEntity.setType(abutmentProduction.getSmallType());
//                    productionEntity.setStatus(0);
//                    productionEntity.setProductionBomStatus(0);
//                    productionEntity.setProductionProcessConnectStatus(0);
//                    productionEntity.setProcessStatus(0);
//                    productionEntity.setCreateTime(new Date());
//                    buildConnectOrderStatus(productionEntity);
//                    //产品物料编码查询的工序不为空
//                    if(CollectionUtil.isNotEmpty(abutmentProduction.getConnectProcessCrafts())){
//                        ProcessEntity processEntity = new ProcessEntity();
//                        processEntity.setName(abutmentProduction.getName());
//                        processEntity.setProcessNum(abutmentProduction.getMaterialNo());
//                        String processCode = "process-" + UUIDUtil.getUUID();
//                        processEntity.setCode(processCode);
//                        processEntity.setVersion(CommonConstant.INIT_VERSION);
//                        processEntity.setCreateTime(new Date());
//                        processEntity.setStatus(0);
//                        abutmentProduction.getConnectProcessCrafts().forEach(abutmentProcessCraft -> {
//                            ProcessCraftEntity processCraftEntity = new ProcessCraftEntity();
//                            BeanUtil.copyProperties(abutmentProcessCraft , processCraftEntity);
//                            processCraftEntity.setProcessCode(processCode);
//                            processCraftEntity.setCode("craft-"+UUIDUtil.getUUID());
//                            processCraftEntity.setVersion(1);
//                            processCraftEntity.setSingleTimeConsuming(BigDecimal.valueOf(abutmentProcessCraft.getSingleTime()));
//                            //if(CollectionUtil.isNotEmpty())
//                        });
//                        //ProductionProcessEntity productionProcessEntity = new ProductionProcessEntity();
//                    }
//                });
//            }
//        }
//        return null;
//    }

    /**
     * 拉取数据手动关联
     * @return
     */
    public Object abutmentProduction() {
        List<AbutmentProductionEntity> abutmentProductions = querySqlServerService.abutmentProduction();
            if(CollectionUtil.isNotEmpty(abutmentProductions)){
                List<ProductionEntity> addProductionEntities = new ArrayList<>();
                List<ProductionEntity> updateProductionEntities = new ArrayList<>();
                List<ProcessEntity> addProcessEntities = new ArrayList<>();
                List<ProcessCraftEntity> addProcessCraftEntities = new ArrayList<>();
                abutmentProductions.forEach(abutmentProduction -> {
                    if(StringUtils.isEmpty(abutmentProduction.getFigureNo())){
                        return;
                    }
                    QueryWrapper<ProductionEntity> wrapper = new QueryWrapper<>();
                    wrapper.eq("material_no" , abutmentProduction.getMaterialNo());
                    ProductionEntity existProduction = productionMapper.selectOne(wrapper);
                    if(ObjectUtil.isNotNull(existProduction)){
                        //已存在
                        BeanUtil.copyProperties(abutmentProduction , existProduction);
                        existProduction.setHeavy(BigDecimal.valueOf(abutmentProduction.getProductionHeavy()));
                        existProduction.setType(abutmentProduction.getSmallType());
                        existProduction.setModifyTime(new Date());
                        buildConnectOrderStatus(existProduction);
                        updateProductionEntities.add(existProduction);
                        return;
                    }
                    //不存在
                    ProductionEntity productionEntity = new ProductionEntity();
                    BeanUtil.copyProperties(abutmentProduction , productionEntity);
                    productionEntity.setHeavy(BigDecimal.valueOf(abutmentProduction.getProductionHeavy()));
                    productionEntity.setType(abutmentProduction.getSmallType());
                    productionEntity.setStatus(0);
                    productionEntity.setProductionBomStatus(0);
                    productionEntity.setProductionProcessConnectStatus(0);
                    productionEntity.setProcessStatus(0);
                    productionEntity.setCreateTime(new Date());
                    buildConnectOrderStatus(productionEntity);
                    addProductionEntities.add(productionEntity);
                    //产品物料编码查询的工序不为空
                    if(CollectionUtil.isNotEmpty(abutmentProduction.getConnectProcessCrafts())){
                        ProcessEntity processEntity = new ProcessEntity();
                        processEntity.setName(abutmentProduction.getName());
                        processEntity.setProcessNum(abutmentProduction.getMaterialNo());
                        String processCode = "process-" + UUIDUtil.getUUID();
                        processEntity.setCode(processCode);
                        processEntity.setVersion(CommonConstant.INIT_VERSION);
                        processEntity.setCreateTime(new Date());
                        processEntity.setStatus(0);
                        addProcessEntities.add(processEntity);
                        abutmentProduction.getConnectProcessCrafts().forEach(abutmentProcessCraft -> {
                            ProcessCraftEntity processCraftEntity = new ProcessCraftEntity();
                            BeanUtil.copyProperties(abutmentProcessCraft , processCraftEntity);
                            processCraftEntity.setProcessCode(processCode);
                            processCraftEntity.setCode("craft-"+UUIDUtil.getUUID());
                            processCraftEntity.setSingleTimeConsuming(BigDecimal.valueOf(abutmentProcessCraft.getSingleTime()));
                            addProcessCraftEntities.add(processCraftEntity);
                        });
                    }
                });
                //批量新增产品
                if(CollectionUtil.isNotEmpty(addProductionEntities)){
                    productionMapper.insertBatchSomeColumn(addProductionEntities);
                }
                //批量修改产品
                if(CollectionUtil.isNotEmpty(updateProductionEntities)){
                    productionMapper.updateBatchById(updateProductionEntities);
                }
                //批量新增工艺
                if(CollectionUtil.isNotEmpty(addProcessEntities)){
                    processMapper.insertBatchSomeColumn(addProcessEntities);
                }
                //批量新增工艺工序
                if(CollectionUtil.isNotEmpty(addProcessCraftEntities)){
                    processCraftMapper.insertBatchSomeColumn(addProcessCraftEntities);
                }
            }

        return null;
    }

    @DSTransactional
    public Object abutmentProductionReload(List<String> materialNos) {
        List<AbutmentProductionEntity> abutmentProductions = querySqlServerService.abutmentProduction(materialNos);
        if(CollectionUtil.isNotEmpty(abutmentProductions)){
            List<ProductionEntity> addProductionEntities = new ArrayList<>();
            List<ProductionEntity> updateProductionEntities = new ArrayList<>();
            List<ProcessEntity> addProcessEntities = new ArrayList<>();
            List<ProcessCraftEntity> addProcessCraftEntities = new ArrayList<>();
            List<ProductionBomEntity> addProductionBomEntities = new ArrayList<>();
            List<ProductionBomEntity> updateProductionBomEntities = new ArrayList<>();
            abutmentProductions.forEach(abutmentProduction -> {
                String figureNo = abutmentProduction.getMaterialNo();
                QueryWrapper<ProductionEntity> wrapper = new QueryWrapper<>();
                wrapper.eq("material_no" , abutmentProduction.getMaterialNo());
                ProductionEntity existProduction = productionMapper.selectOne(wrapper);
                if(ObjectUtil.isNotNull(existProduction)){
                    //产品查询的物料bom信息不为空
                    if(CollectionUtil.isNotEmpty(abutmentProduction.getConnectProductionBom())){
                        existProduction.setProductionBomStatus(1);
                        abutmentProduction.getConnectProductionBom().forEach(abutmentProductionBomEntity -> {
                            ProductionBomEntity existProductionBomEntity = productionBomMapper.selectById(abutmentProductionBomEntity.getId());
                            if(ObjectUtil.isNotNull(existProductionBomEntity)){
                                BeanUtil.copyProperties(abutmentProductionBomEntity , existProductionBomEntity);
                                existProductionBomEntity.setFigureNo(figureNo);
                                existProductionBomEntity.setVersion(CommonConstant.INIT_VERSION);
                                updateProductionBomEntities.add(existProductionBomEntity);
                            }else{
                                ProductionBomEntity productionBomEntity = new ProductionBomEntity();
                                productionBomEntity.setCode("bom"+ UUIDUtil.getUUID());
//                            BeanUtil.copyProperties(abutmentProductionBomEntity , productionBomEntity);
                                productionBomEntity.setName(abutmentProductionBomEntity.getName());
                                productionBomEntity.setDescription(abutmentProductionBomEntity.getDescription());
                                productionBomEntity.setSeq(abutmentProductionBomEntity.getSeq());
                                productionBomEntity.setQuantity(abutmentProductionBomEntity.getQuantity().intValue());
                                productionBomEntity.setUnit(abutmentProductionBomEntity.getUnit());
                                productionBomEntity.setFigureNo(figureNo);
                                productionBomEntity.setVersion(CommonConstant.INIT_VERSION);
                                addProductionBomEntities.add(productionBomEntity);
                            }
                        });
                    }
                    updateProductionEntities.add(existProduction);
                    return;
                }
            });
            //批量新增产品
            if(CollectionUtil.isNotEmpty(addProductionEntities)){
                productionMapper.insertBatchSomeColumn(addProductionEntities);
            }
            //批量修改产品
            if(CollectionUtil.isNotEmpty(updateProductionEntities)){
                productionMapper.updateBatchById(updateProductionEntities);
            }
            //批量新增工艺
            if(CollectionUtil.isNotEmpty(addProcessEntities)){
                processMapper.insertBatchSomeColumn(addProcessEntities);
            }
            //批量新增工艺工序
            if(CollectionUtil.isNotEmpty(addProcessCraftEntities)){
                processCraftMapper.insertBatchSomeColumn(addProcessCraftEntities);
            }
            //批量新增产品物料
            if(CollectionUtil.isNotEmpty(addProductionBomEntities)){
                productionBomMapper.insertBatchSomeColumn(addProductionBomEntities);
            }
            //批量修改产品物料
            if(CollectionUtil.isNotEmpty(updateProductionBomEntities)){
                productionBomMapper.updateBatchById(updateProductionBomEntities);
            }
        }
        return null;
    }

    @DSTransactional
    public Object abutmentProductionReload1(List<Map<String , String>> materialNos) {
        List<AbutmentProductionEntity> abutmentProductions = querySqlServerService.abutmentProductionReload1(materialNos);
        if(CollectionUtil.isNotEmpty(abutmentProductions)){
            List<ProductionEntity> addProductionEntities = new ArrayList<>();
            List<ProductionEntity> updateProductionEntities = new ArrayList<>();
            List<ProcessEntity> addProcessEntities = new ArrayList<>();
            List<ProcessCraftEntity> addProcessCraftEntities = new ArrayList<>();
            List<ProductionBomEntity> addProductionBomEntities = new ArrayList<>();
            List<ProductionBomEntity> updateProductionBomEntities = new ArrayList<>();
            abutmentProductions.forEach(abutmentProduction -> {
//                if(StringUtils.isEmpty(abutmentProduction.getFigureNo())){
//                    return;
//                }
                String figureNo = abutmentProduction.getMaterialNo();
                String figureNo1 = abutmentProduction.getFigureNo();
                QueryWrapper<ProductionEntity> wrapper = new QueryWrapper<>();
                wrapper.eq("material_no" , abutmentProduction.getMaterialNo());
                ProductionEntity existProduction = productionMapper.selectOne(wrapper);
                if(ObjectUtil.isNotNull(existProduction)){
                    //已存在
                    BeanUtil.copyProperties(abutmentProduction , existProduction);
                    existProduction.setHeavy(BigDecimal.valueOf(abutmentProduction.getProductionHeavy()));
                    existProduction.setType(abutmentProduction.getSmallType());
                    existProduction.setModifyTime(new Date());
                    existProduction.setFigureNoReload(figureNo1);
                    buildConnectOrderStatus(existProduction);
                    updateProductionEntities.add(existProduction);
                    return;
                }
                //不存在
                ProductionEntity productionEntity = new ProductionEntity();
                BeanUtil.copyProperties(abutmentProduction , productionEntity);
                productionEntity.setHeavy(BigDecimal.valueOf(abutmentProduction.getProductionHeavy()));
                productionEntity.setType(abutmentProduction.getSmallType());
                productionEntity.setFigureNoReload(figureNo1);
                productionEntity.setStatus(0);
                productionEntity.setProductionBomStatus(0);
                productionEntity.setProductionProcessConnectStatus(0);
                productionEntity.setProcessStatus(0);
                productionEntity.setCreateTime(new Date());
                buildConnectOrderStatus(productionEntity);
                //产品查询的物料bom信息不为空
                if(CollectionUtil.isNotEmpty(abutmentProduction.getConnectProductionBom())){
                    productionEntity.setProductionBomStatus(1);
                    abutmentProduction.getConnectProductionBom().forEach(abutmentProductionBomEntity -> {
                        ProductionBomEntity existProductionBomEntity = productionBomMapper.selectById(abutmentProductionBomEntity.getId());
                        if(ObjectUtil.isNotNull(existProductionBomEntity)){
                            BeanUtil.copyProperties(abutmentProductionBomEntity , existProductionBomEntity);
                            existProductionBomEntity.setFigureNo(figureNo);
                            existProductionBomEntity.setVersion(CommonConstant.INIT_VERSION);
                            updateProductionBomEntities.add(existProductionBomEntity);
                        }else{
                            ProductionBomEntity productionBomEntity = new ProductionBomEntity();
                            productionBomEntity.setCode("bom"+ UUIDUtil.getUUID());
                            BeanUtil.copyProperties(abutmentProductionBomEntity , productionBomEntity);
                            productionBomEntity.setFigureNo(figureNo);
                            productionBomEntity.setVersion(CommonConstant.INIT_VERSION);
                            addProductionBomEntities.add(productionBomEntity);
                        }
                    });
                }
                addProductionEntities.add(productionEntity);
                //产品物料编码查询的工序不为空
                if(CollectionUtil.isNotEmpty(abutmentProduction.getConnectProcessCrafts())){
                    ProcessEntity processEntity = new ProcessEntity();
                    processEntity.setName(abutmentProduction.getName());
                    processEntity.setProcessNum(abutmentProduction.getMaterialNo());
                    String processCode = "process-" + UUIDUtil.getUUID();
                    processEntity.setCode(processCode);
                    processEntity.setVersion(CommonConstant.INIT_VERSION);
                    processEntity.setCreateTime(new Date());
                    processEntity.setStatus(0);
                    addProcessEntities.add(processEntity);
                    abutmentProduction.getConnectProcessCrafts().forEach(abutmentProcessCraft -> {
                        ProcessCraftEntity processCraftEntity = new ProcessCraftEntity();
                        BeanUtil.copyProperties(abutmentProcessCraft , processCraftEntity);
                        processCraftEntity.setAdjust(abutmentProcessCraft.getSingleTime());
                        processCraftEntity.setProcessCode(processCode);
                        processCraftEntity.setVersion(CommonConstant.INIT_VERSION);
                        processCraftEntity.setCode("craft-"+UUIDUtil.getUUID());
                        processCraftEntity.setSingleTimeConsuming(BigDecimal.valueOf(abutmentProcessCraft.getSingleTime()));
                        addProcessCraftEntities.add(processCraftEntity);
                    });
                }
            });
            //批量新增产品
            if(CollectionUtil.isNotEmpty(addProductionEntities)){
                productionMapper.insertBatchSomeColumn(addProductionEntities);
            }
            //批量修改产品
            if(CollectionUtil.isNotEmpty(updateProductionEntities)){
                productionMapper.updateBatchById(updateProductionEntities);
            }
            //批量新增工艺
            if(CollectionUtil.isNotEmpty(addProcessEntities)){
                processMapper.insertBatchSomeColumn(addProcessEntities);
            }
            //批量新增工艺工序
            if(CollectionUtil.isNotEmpty(addProcessCraftEntities)){
                processCraftMapper.insertBatchSomeColumn(addProcessCraftEntities);
            }
            //批量新增产品物料
            if(CollectionUtil.isNotEmpty(addProductionBomEntities)){
                productionBomMapper.insertBatchSomeColumn(addProductionBomEntities);
            }
            //批量修改产品物料
            if(CollectionUtil.isNotEmpty(updateProductionBomEntities)){
                productionBomMapper.updateBatchById(updateProductionBomEntities);
            }
        }
        return null;
    }

    public void abutmentDataConnect(String materialNo) {

    }

    public void exportProductionTemplate(HttpServletResponse response) {
        String outputFileName = "产品导入模版";
        //ToolUsageReportExport toolUsageReportExport = buildToolUsageReport(taskId);
        CommonUtil.exportExcelFile(new Object() , "/template/production/产品导入模版.xlsx" , response , outputFileName);
    }

    @Transactional
    public void importProductionTemplate(List<List<LinkedHashMap>> dataList) {
        List<ProductionEntity> insertProductionList = new ArrayList<>();
        List<ProductionBomEntity> insertBomList = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(dataList)){
            for (List<LinkedHashMap> mapList : dataList) {
                LinkedHashMap linkedHashMap1 = mapList.get(0);
                LinkedHashMap linkedHashMap2 = mapList.get(1);
                String productionName = linkedHashMap1.get("1").toString();
                String materialNos = linkedHashMap2.get("1").toString();
                String figureNo = linkedHashMap2.get("3").toString();
                String productionNum = linkedHashMap1.get("3").toString();
                //校验数据
                if(ObjectUtil.isNull(productionName) || ObjectUtil.isNull(materialNos)
                        || ObjectUtil.isNull(figureNo) || ObjectUtil.isNull(productionNum)){
                    return;
                }
                //校验是否冲突
                List<ProductionEntity> productionEntities = productionMapper.selectList(new QueryWrapper<>());
                if(CollectionUtil.isNotEmpty(productionEntities)){
                    List<String> existMaterialNos = productionEntities.stream().map(ProductionEntity::getMaterialNo).collect(Collectors.toList());
                    List<String> existFigureNos = productionEntities.stream().map(ProductionEntity::getFigureNo).collect(Collectors.toList());
                    List<String> existProductionNum = productionEntities.stream().map(ProductionEntity::getProductionNum).collect(Collectors.toList());
                    if(existMaterialNos.contains(materialNos) || existFigureNos.contains(figureNo) || existProductionNum.contains(productionNum)){
                        return;
                    }
                }
                //保存产品基础数据
                ProductionEntity productionEntity = new ProductionEntity();
                productionEntity.setName(productionName);
                productionEntity.setHeavy(new BigDecimal(linkedHashMap1.get("5").toString()));
                productionEntity.setMaterialNo(materialNos);
                productionEntity.setFigureNo(figureNo);
                productionEntity.setFigureNoReload(figureNo);
                productionEntity.setType(linkedHashMap2.get("5").toString());
                productionEntity.setProductionNum(productionNum);
                productionEntity.setStatus(0);
                productionEntity.setProductionBomStatus(0);
                productionEntity.setProcessStatus(0);
                productionEntity.setProductionProcessConnectStatus(0);
                productionEntity.setCreateTime(new Date());
                insertProductionList.add(productionEntity);
                //保存bom信息
                if(mapList.size() > 3){
                    productionEntity.setProductionBomStatus(1);
                    for (int i = 3; i < mapList.size(); i++) {
                        LinkedHashMap linkedHashMap = mapList.get(i);
                        ProductionBomEntity productionBomEntity = new ProductionBomEntity();
                        productionBomEntity.setVersion(1);
                        productionBomEntity.setCode("bom" + "-" + UUIDUtil.getUUID());
                        productionBomEntity.setName(linkedHashMap.get("1").toString());
                        try{
                            productionBomEntity.setSeq(Integer.valueOf(linkedHashMap.get("0").toString()));
                        }catch (Exception e){

                        }
                        try{
                            productionBomEntity.setQuantity(Integer.valueOf(linkedHashMap.get("2").toString()));
                        }catch (Exception e){

                        }
                        productionBomEntity.setUnit(linkedHashMap.get("4").toString());
                        productionBomEntity.setDescription(linkedHashMap.get("3").toString());
                        productionBomEntity.setFigureNo(materialNos);
                        insertBomList.add(productionBomEntity);
                    }
                }
            }
        }
        //持久化产品基础信息
        if(CollectionUtil.isNotEmpty(insertProductionList)){
            productionMapper.insertBatchSomeColumn(insertProductionList);
        }
        //持久化产品bom信息
        if(CollectionUtil.isNotEmpty(insertBomList)){
            productionBomMapper.insertBatchSomeColumn(insertBomList);
        }
    }

    static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }

//    /**
//     * 拉取数据手动关联
//     * @return
//     */
//    public Object abutmentProduction() {
//        //String get = HttpUtil.get(UrlConstant.PROCESS_MANAGEMENT_SYNC_URL + "/abutmentProduction");
//        List<AbutmentProductionEntity> abutmentProductions = testService.test3();
////            List<AbutmentProduction> abutmentProductions = JSONArray.parseArray(get, AbutmentProduction.class);
//            if(CollectionUtil.isNotEmpty(abutmentProductions)){
//                List<ProductionEntity> addProductionEntities = new ArrayList<>();
//                List<ProductionEntity> updateProductionEntities = new ArrayList<>();
//                List<ProcessEntity> addProcessEntities = new ArrayList<>();
//                List<ProcessCraftEntity> addProcessCraftEntities = new ArrayList<>();
//                abutmentProductions.forEach(abutmentProduction -> {
//                    if(StringUtils.isEmpty(abutmentProduction.getFigureNo())){
//                        return;
//                    }
//                    QueryWrapper<ProductionEntity> wrapper = new QueryWrapper<>();
//                    wrapper.eq("material_no" , abutmentProduction.getMaterialNo());
//                    ProductionEntity existProduction = productionMapper.selectOne(wrapper);
//                    if(ObjectUtil.isNotNull(existProduction)){
//                        //已存在
//                        BeanUtil.copyProperties(abutmentProduction , existProduction);
//                        existProduction.setHeavy(BigDecimal.valueOf(abutmentProduction.getProductionHeavy()));
//                        existProduction.setType(abutmentProduction.getSmallType());
//                        existProduction.setModifyTime(new Date());
//                        buildConnectOrderStatus(existProduction);
//                        updateProductionEntities.add(existProduction);
//                        return;
//                    }
//                    //不存在
//                    ProductionEntity productionEntity = new ProductionEntity();
//                    BeanUtil.copyProperties(abutmentProduction , productionEntity);
//                    productionEntity.setHeavy(BigDecimal.valueOf(abutmentProduction.getProductionHeavy()));
//                    productionEntity.setType(abutmentProduction.getSmallType());
//                    productionEntity.setStatus(0);
//                    productionEntity.setProductionBomStatus(0);
//                    productionEntity.setProductionProcessConnectStatus(0);
//                    productionEntity.setProcessStatus(0);
//                    productionEntity.setCreateTime(new Date());
//                    buildConnectOrderStatus(productionEntity);
//                    addProductionEntities.add(productionEntity);
//                    //产品物料编码查询的工序不为空
//                    if(CollectionUtil.isNotEmpty(abutmentProduction.getConnectProcessCrafts())){
//                        ProcessEntity processEntity = new ProcessEntity();
//                        processEntity.setName(abutmentProduction.getName());
//                        processEntity.setProcessNum(abutmentProduction.getMaterialNo());
//                        String processCode = "process-" + UUIDUtil.getUUID();
//                        processEntity.setCode(processCode);
//                        processEntity.setVersion(CommonConstant.INIT_VERSION);
//                        processEntity.setCreateTime(new Date());
//                        processEntity.setStatus(0);
//                        addProcessEntities.add(processEntity);
//                        abutmentProduction.getConnectProcessCrafts().forEach(abutmentProcessCraft -> {
//                            ProcessCraftEntity processCraftEntity = new ProcessCraftEntity();
//                            BeanUtil.copyProperties(abutmentProcessCraft , processCraftEntity);
//                            processCraftEntity.setProcessCode(processCode);
//                            processCraftEntity.setCode("craft-"+UUIDUtil.getUUID());
//                            processCraftEntity.setSingleTimeConsuming(BigDecimal.valueOf(abutmentProcessCraft.getSingleTime()));
//                            processCraftEntity.setVersion(1);
//                            addProcessCraftEntities.add(processCraftEntity);
//                        });
//                    }
//                });
//                //批量新增产品
//                if(CollectionUtil.isNotEmpty(addProductionEntities)){
//                    productionMapper.insertBatchSomeColumn(addProductionEntities);
//                }
//                //批量修改产品
//                if(CollectionUtil.isNotEmpty(updateProductionEntities)){
//                    productionMapper.updateBatchById(updateProductionEntities);
//                }
//                //批量新增工艺
//                if(CollectionUtil.isNotEmpty(addProcessEntities)){
//                    processMapper.insertBatchSomeColumn(addProcessEntities);
//                }
//                //批量新增工艺工序
//                if(CollectionUtil.isNotEmpty(addProcessCraftEntities)){
//                    processCraftMapper.insertBatchSomeColumn(addProcessCraftEntities);
//                }
//            }
//
//        return null;
//    }

//    public Object abutmentProductionReload(List<String> materialNos) {
//        //String get = HttpUtil.get(UrlConstant.PROCESS_MANAGEMENT_SYNC_URL + "/abutmentProduction");
//        List<AbutmentProductionEntity> abutmentProductions = testService.test3(materialNos);
////            List<AbutmentProduction> abutmentProductions = JSONArray.parseArray(get, AbutmentProduction.class);
//        if(CollectionUtil.isNotEmpty(abutmentProductions)){
//            List<ProductionEntity> addProductionEntities = new ArrayList<>();
//            List<ProductionEntity> updateProductionEntities = new ArrayList<>();
//            List<ProcessEntity> addProcessEntities = new ArrayList<>();
//            List<ProcessCraftEntity> addProcessCraftEntities = new ArrayList<>();
//            abutmentProductions.forEach(abutmentProduction -> {
//                if(StringUtils.isEmpty(abutmentProduction.getFigureNo())){
//                    return;
//                }
//                QueryWrapper<ProductionEntity> wrapper = new QueryWrapper<>();
//                wrapper.eq("material_no" , abutmentProduction.getMaterialNo());
//                ProductionEntity existProduction = productionMapper.selectOne(wrapper);
//                if(ObjectUtil.isNotNull(existProduction)){
//                    //已存在
//                    BeanUtil.copyProperties(abutmentProduction , existProduction);
//                    existProduction.setHeavy(BigDecimal.valueOf(abutmentProduction.getProductionHeavy()));
//                    existProduction.setType(abutmentProduction.getSmallType());
//                    existProduction.setModifyTime(new Date());
//                    buildConnectOrderStatus(existProduction);
//                    updateProductionEntities.add(existProduction);
//                    return;
//                }
//                //不存在
//                ProductionEntity productionEntity = new ProductionEntity();
//                BeanUtil.copyProperties(abutmentProduction , productionEntity);
//                productionEntity.setHeavy(BigDecimal.valueOf(abutmentProduction.getProductionHeavy()));
//                productionEntity.setType(abutmentProduction.getSmallType());
//                productionEntity.setStatus(0);
//                productionEntity.setProductionBomStatus(0);
//                productionEntity.setProductionProcessConnectStatus(0);
//                productionEntity.setProcessStatus(0);
//                productionEntity.setCreateTime(new Date());
//                buildConnectOrderStatus(productionEntity);
//                addProductionEntities.add(productionEntity);
//                //产品物料编码查询的工序不为空
//                if(CollectionUtil.isNotEmpty(abutmentProduction.getConnectProcessCrafts())){
//                    ProcessEntity processEntity = new ProcessEntity();
//                    processEntity.setName(abutmentProduction.getName());
//                    processEntity.setProcessNum(abutmentProduction.getMaterialNo());
//                    String processCode = "process-" + UUIDUtil.getUUID();
//                    processEntity.setCode(processCode);
//                    processEntity.setVersion(CommonConstant.INIT_VERSION);
//                    processEntity.setCreateTime(new Date());
//                    processEntity.setStatus(0);
//                    addProcessEntities.add(processEntity);
//                    abutmentProduction.getConnectProcessCrafts().forEach(abutmentProcessCraft -> {
//                        ProcessCraftEntity processCraftEntity = new ProcessCraftEntity();
//                        BeanUtil.copyProperties(abutmentProcessCraft , processCraftEntity);
//                        processCraftEntity.setProcessCode(processCode);
//                        processCraftEntity.setCode("craft-"+UUIDUtil.getUUID());
//                        processCraftEntity.setVersion(CommonConstant.INIT_VERSION);
//                        processCraftEntity.setSingleTimeConsuming(BigDecimal.valueOf(abutmentProcessCraft.getSingleTime()));
//                        addProcessCraftEntities.add(processCraftEntity);
//                    });
//                }
//            });
//            //批量新增产品
//            if(CollectionUtil.isNotEmpty(addProductionEntities)){
//                productionMapper.insertBatchSomeColumn(addProductionEntities);
//            }
//            //批量修改产品
//            if(CollectionUtil.isNotEmpty(updateProductionEntities)){
//                productionMapper.updateBatchById(updateProductionEntities);
//            }
//            //批量新增工艺
//            if(CollectionUtil.isNotEmpty(addProcessEntities)){
//                processMapper.insertBatchSomeColumn(addProcessEntities);
//            }
//            //批量新增工艺工序
//            if(CollectionUtil.isNotEmpty(addProcessCraftEntities)){
//                processCraftMapper.insertBatchSomeColumn(addProcessCraftEntities);
//            }
//        }
//
//        return null;
//    }
}
